package cn.zz.veggie.persistence.repository;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.zz.comm.util.DateUtil;
import cn.zz.veggie.model.domain.Sequence;
import cn.zz.veggie.persistence.dao.SequenceMapper;
import lombok.RequiredArgsConstructor;

/**
 * @author zhongq
 * @since 2024/7/14
 */
@Repository
@RequiredArgsConstructor
public class SequenceRepository {
	public static final int order_sn_seq = 1;

	private final SequenceMapper sequenceMapper;

	/**
	 * 订单的sn 并以非事务的方式运行
	 */
	@Transactional(propagation = Propagation.NOT_SUPPORTED)
	public String genOrderSn(int uid) {
		// 8 + 4
		String datePrefix = DateUtil.now().format(DateUtil.PURE_DATETIME_FORMATTER);
		final int seqNumber = nextSeq(order_sn_seq) % 10000;
		return datePrefix + String.format("%04d", uid) + String.format("%04d", seqNumber);
	}

	private int nextSeq(int type) {
		final long dateTime = DateUtil.dayStart(0);
		// 查询当天的序列记录
		LambdaQueryWrapper<Sequence> queryWrapper = Wrappers.lambdaQuery();
		queryWrapper.eq(Sequence::getType, type);
		queryWrapper.eq(Sequence::getCreatedAt, dateTime);

		Sequence sequence = sequenceMapper.selectOne(queryWrapper);
		if (sequence == null) {
			sequence = new Sequence();
			sequence.setType(type);
			sequence.setSeq(1);
			sequence.setCreatedAt(dateTime);
			sequenceMapper.insert(sequence);
			return 1;
		} else {
			// 如果有记录，将当前值加 1 并更新
			int nextValue = sequence.getSeq() + 1;
			sequence.setSeq(nextValue);
			sequenceMapper.updateById(sequence);
			return nextValue;
		}
	}

}